package controller;

import pojo.Admin;
import service.AdminService;
import service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/LoginController")
public class  LoginController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        获取登录信息
        String username = req.getParameter("username");
        String passwork = req.getParameter("passwork");
//        调用业务层判断密码
        AdminService service = new AdminServiceImpl();
        Admin admin = service.login(username, passwork);
        if (admin != null) {
//            存在放cookie
            Cookie cookie = new Cookie("loginName", admin.getUsername());
            cookie.setMaxAge(3600 * 24 * 7);
            resp.addCookie(cookie);
//用户信息存入session中  判断登录
            req.getSession().setAttribute("admin", admin);
//重定向到主页面
            resp.sendRedirect(req.getContextPath()+"/admin/main.jsp");
        } else {

            req.setAttribute("loginError", "用户名或密码错误");

        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
